package com.chenjj.java.spring.spel.impl;

import com.chenjj.java.spring.spel.SpelService;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class SpelServiceImpl implements SpelService {


    @Override
    public <T> T getValueFromObj(String spel, Object obj,T type) {
        //解析器
        ExpressionParser parser = new SpelExpressionParser();
        //表达式 -- 模板，允许前缀#{ 后缀}
        //Expression expression = parser.parseExpression(spel,new TemplateParserContext());
        //表达式 -- 没模板
        Expression expression = parser.parseExpression(spel);
        //解析上下文
        EvaluationContext context=new StandardEvaluationContext(obj);

        T value = (T) expression.getValue(context);

        return value;
    }

    @Override
    public <T> T getValueFromText(String text) {
        return null;
    }
}
